import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus';
import { addGangItemAPI, updateGangItemAPI } from "../../api/gang";

/**
 * @description: 新增/编辑表单
 * @param {Function} query 查询列表方法
 * @return {*}
 */
export default function useForm(query: Function) {
    // 表单相关
    const dialogVisible = ref(false);
    const formRef = ref();
    const isEdit = ref(false);
    const upload = ref();
    const editor = ref();
    const form = reactive({
        id: '',
        title: '',
        publishTime: '',
        content: ''
    })

    // 新增/编辑 操作
    const handleEdit = (item: any) => {
        // 编辑回填
        if (item) {
            isEdit.value = true;
            form.id = item.id
            form.title = item.title
            form.publishTime = item.publishTime
            form.content = item.content
        }
        // 新增清空
        else {
            isEdit.value = false;
            form.id = "";
            form.title = "";
            form.publishTime = "";
            form.content = "";
        }
        dialogVisible.value = true;
    };

    // 确定 新增/编辑 操作
    const handleConfirm = () => {
        formRef.value.validate((valid: any, fields: any) => {
            if (valid) {
                let addAPI = isEdit.value ? updateGangItemAPI : addGangItemAPI
                addAPI({ ...form, content: editor.value.valueHtml }).then(res => {
                    if (res.code === 200) {
                        ElMessage({
                            message: isEdit.value ? '编辑成功' : '新建成功',
                            type: 'success',
                        })
                    }
                    dialogVisible.value = false;
                    query();
                })
            } else {

            }
        })
    }
   
    return {
        dialogVisible,
        formRef,
        isEdit,
        form,
        upload,
        editor,
        handleEdit,
        handleConfirm,
    }
}